package com.wang;
//使用线程模拟 实现多人同时在一个账户中取钱
public class Bank {
    public static void main(String[] args) {
        //创建账户
        BankAccount bankAccount = new BankAccount(10000);
        //开4个线程 在同一个账户取钱
        new PersonThread("wang",bankAccount).start();
        new PersonThread("zhang",bankAccount).start();
        new PersonThread("liu",bankAccount).start();
        new PersonThread("niu",bankAccount).start();
    }

}
//定义用户， 定义线程类
class PersonThread extends  Thread{
    //账户
    private BankAccount bankAccount;
    //这个用来指定人,账户
    public PersonThread(String name, BankAccount bankAccount) {
        super(name);
        this.bankAccount = bankAccount;
    }

    @Override
    public void run() {
        //上锁
        synchronized (bankAccount) {
            System.out.println(Thread.currentThread().getName()+"查询余额"+bankAccount.getBalance());
            bankAccount.withdraw(1000);
            System.out.println(Thread.currentThread().getName()+"取1000元后，余额还有"+bankAccount.getBalance());
        }
    }
}
//定义一个银行账户类
class BankAccount{
    private int balance;
    public  BankAccount(int balance){
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    public void withdraw(int money){
        balance -= money;
    }
}
